home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / test / regrtest.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-11-11  |  31.4 KB  |  922 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Regression test.
  5.  
  6. This will find all modules whose name is "test_*" in the test
  7. directory, and run them.  Various command line options provide
  8. additional facilities.
  9.  
  10. Command line options:
  11.  
  12. -v: verbose    -- run tests in verbose mode with output to stdout
  13. -w: verbose2   -- re-run failed tests in verbose mode
  14. -q: quiet      -- don\'t print anything except if a test fails
  15. -x: exclude    -- arguments are tests to *exclude*
  16. -s: single     -- run only a single test (see below)
  17. -S: slow       -- print the slowest 10 tests
  18. -r: random     -- randomize test execution order
  19. -f: fromfile   -- read names of tests to run from a file (see below)
  20. -l: findleaks  -- if GC is available detect tests that leak memory
  21. -u: use        -- specify which special resource intensive tests to run
  22. -h: help       -- print this text and exit
  23. -t: threshold  -- call gc.set_threshold(N)
  24. -T: coverage   -- turn on code coverage using the trace module
  25. -D: coverdir   -- Directory where coverage files are put
  26. -N: nocoverdir -- Put coverage files alongside modules
  27. -L: runleaks   -- run the leaks(1) command just before exit
  28. -R: huntrleaks -- search for reference leaks (needs debug build, v. slow)
  29. -M: memlimit   -- run very large memory-consuming tests
  30.  
  31. If non-option arguments are present, they are names for tests to run,
  32. unless -x is given, in which case they are names for tests not to run.
  33. If no test names are given, all tests are run.
  34.  
  35. -T turns on code coverage tracing with the trace module.
  36.  
  37. -D specifies the directory where coverage files are put.
  38.  
  39. -N Put coverage files alongside modules.
  40.  
  41. -s means to run only a single test and exit.  This is useful when
  42. doing memory analysis on the Python interpreter (which tend to consume
  43. too many resources to run the full regression test non-stop).  The
  44. file /tmp/pynexttest is read to find the next test to run.  If this
  45. file is missing, the first test_*.py file in testdir or on the command
  46. line is used.  (actually tempfile.gettempdir() is used instead of
  47. /tmp).
  48.  
  49. -f reads the names of tests from the file given as f\'s argument, one
  50. or more test names per line.  Whitespace is ignored.  Blank lines and
  51. lines beginning with \'#\' are ignored.  This is especially useful for
  52. whittling down failures involving interactions among tests.
  53.  
  54. -L causes the leaks(1) command to be run just before exit if it exists.
  55. leaks(1) is available on Mac OS X and presumably on some other
  56. FreeBSD-derived systems.
  57.  
  58. -R runs each test several times and examines sys.gettotalrefcount() to
  59. see if the test appears to be leaking references.  The argument should
  60. be of the form stab:run:fname where \'stab\' is the number of times the
  61. test is run to let gettotalrefcount settle down, \'run\' is the number
  62. of times further it is run and \'fname\' is the name of the file the
  63. reports are written to.  These parameters all have defaults (5, 4 and
  64. "reflog.txt" respectively), so the minimal invocation is \'-R ::\'.
  65.  
  66. -M runs tests that require an exorbitant amount of memory. These tests
  67. typically try to ascertain containers keep working when containing more than
  68. 2 billion objects, which only works on 64-bit systems. There are also some
  69. tests that try to exhaust the address space of the process, which only makes
  70. sense on 32-bit systems with at least 2Gb of memory. The passed-in memlimit,
  71. which is a string in the form of \'2.5Gb\', determines howmuch memory the
  72. tests will limit themselves to (but they may go slightly over.) The number
  73. shouldn\'t be more memory than the machine has (including swap memory). You
  74. should also keep in mind that swap memory is generally much, much slower
  75. than RAM, and setting memlimit to all available RAM or higher will heavily
  76. tax the machine. On the other hand, it is no use running these tests with a
  77. limit of less than 2.5Gb, and many require more than 20Gb. Tests that expect
  78. to use more than memlimit memory will be skipped. The big-memory tests
  79. generally run very, very long.
  80.  
  81. -u is used to specify which special resource intensive tests to run,
  82. such as those requiring large file support or network connectivity.
  83. The argument is a comma-separated list of words indicating the
  84. resources to test.  Currently only the following are defined:
  85.  
  86.     all -       Enable all special resources.
  87.  
  88.     audio -     Tests that use the audio device.  (There are known
  89.                 cases of broken audio drivers that can crash Python or
  90.                 even the Linux kernel.)
  91.  
  92.     curses -    Tests that use curses and will modify the terminal\'s
  93.                 state and output modes.
  94.  
  95.     lib2to3 -   Run the tests for 2to3 (They take a while.)
  96.  
  97.     largefile - It is okay to run some test that may create huge
  98.                 files.  These tests can take a long time and may
  99.                 consume >2GB of disk space temporarily.
  100.  
  101.     network -   It is okay to run tests that use external network
  102.                 resource, e.g. testing SSL support for sockets.
  103.  
  104.     bsddb -     It is okay to run the bsddb testsuite, which takes
  105.                 a long time to complete.
  106.  
  107.     decimal -   Test the decimal module against a large suite that
  108.                 verifies compliance with standards.
  109.  
  110.     compiler -  Test the compiler package by compiling all the source
  111.                 in the standard library and test suite.  This takes
  112.                 a long time.  Enabling this resource also allows
  113.                 test_tokenize to verify round-trip lexing on every
  114.                 file in the test library.
  115.  
  116.     subprocess  Run all tests for the subprocess module.
  117.  
  118.     urlfetch -  It is okay to download files required on testing.
  119.  
  120. To enable all resources except one, use \'-uall,-<resource>\'.  For
  121. example, to run all the tests except for the bsddb tests, give the
  122. option \'-uall,-bsddb\'.
  123. '''
  124. import cStringIO
  125. import getopt
  126. import os
  127. import random
  128. import re
  129. import sys
  130. import time
  131. import traceback
  132. import warnings
  133. warnings.filterwarnings('ignore', 'hex/oct constants', FutureWarning, '.*test.test_grammar$')
  134. if sys.maxint > 2147483647:
  135.     warnings.filterwarnings('ignore', 'hex/oct constants', FutureWarning, '<string>')
  136.  
  137. for mod in ('ctypes', 'gzip', 'zipfile', 'tarfile', 'encodings.zlib_codec', 'test.test_zipimport', 'test.test_zlib', 'test.test_zipfile', 'test.test_codecs', 'test.string_tests'):
  138.     warnings.filterwarnings(module = '.*%s$' % (mod,), action = 'ignore', category = ImportWarning)
  139.  
  140. if sys.platform == 'darwin':
  141.     
  142.     try:
  143.         import resource
  144.     except ImportError:
  145.         pass
  146.  
  147.     (soft, hard) = resource.getrlimit(resource.RLIMIT_STACK)
  148.     newsoft = min(hard, max(soft, 1024 * 2048))
  149.     resource.setrlimit(resource.RLIMIT_STACK, (newsoft, hard))
  150.  
  151. from test import test_support
  152. RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network', 'bsddb', 'decimal', 'compiler', 'subprocess', 'urlfetch')
  153.  
  154. def usage(code, msg = ''):
  155.     print __doc__
  156.     if msg:
  157.         print msg
  158.     
  159.     sys.exit(code)
  160.  
  161.  
  162. def main(tests = None, testdir = None, verbose = 0, quiet = False, exclude = False, single = False, randomize = False, fromfile = None, findleaks = False, use_resources = None, trace = False, coverdir = 'coverage', runleaks = False, huntrleaks = False, verbose2 = False, print_slow = False):
  163.     """Execute a test suite.
  164.  
  165.     This also parses command-line options and modifies its behavior
  166.     accordingly.
  167.  
  168.     tests -- a list of strings containing test names (optional)
  169.     testdir -- the directory in which to look for tests (optional)
  170.  
  171.     Users other than the Python test suite will certainly want to
  172.     specify testdir; if it's omitted, the directory containing the
  173.     Python test suite is searched for.
  174.  
  175.     If the tests argument is omitted, the tests listed on the
  176.     command-line will be used.  If that's empty, too, then all *.py
  177.     files beginning with test_ will be used.
  178.  
  179.     The other default arguments (verbose, quiet, exclude,
  180.     single, randomize, findleaks, use_resources, trace, coverdir, and
  181.     print_slow) allow programmers calling main() directly to set the
  182.     values that would normally be set by flags on the command line.
  183.     """
  184.     test_support.record_original_stdout(sys.stdout)
  185.     
  186.     try:
  187.         (opts, args) = getopt.getopt(sys.argv[1:], 'hvgqxsSrf:lu:t:TD:NLR:wM:', [
  188.             'help',
  189.             'verbose',
  190.             'quiet',
  191.             'exclude',
  192.             'single',
  193.             'slow',
  194.             'random',
  195.             'fromfile',
  196.             'findleaks',
  197.             'use=',
  198.             'threshold=',
  199.             'trace',
  200.             'coverdir=',
  201.             'nocoverdir',
  202.             'runleaks',
  203.             'huntrleaks=',
  204.             'verbose2',
  205.             'memlimit='])
  206.     except getopt.error:
  207.         msg = None
  208.         usage(2, msg)
  209.  
  210.     if use_resources is None:
  211.         use_resources = []
  212.     
  213.     for o, a in opts:
  214.         if o in ('-h', '--help'):
  215.             usage(0)
  216.             continue
  217.         if o in ('-v', '--verbose'):
  218.             verbose += 1
  219.             continue
  220.         if o in ('-w', '--verbose2'):
  221.             verbose2 = True
  222.             continue
  223.         if o in ('-q', '--quiet'):
  224.             quiet = True
  225.             verbose = 0
  226.             continue
  227.         if o in ('-x', '--exclude'):
  228.             exclude = True
  229.             continue
  230.         if o in ('-s', '--single'):
  231.             single = True
  232.             continue
  233.         if o in ('-S', '--slow'):
  234.             print_slow = True
  235.             continue
  236.         if o in ('-r', '--randomize'):
  237.             randomize = True
  238.             continue
  239.         if o in ('-f', '--fromfile'):
  240.             fromfile = a
  241.             continue
  242.         if o in ('-l', '--findleaks'):
  243.             findleaks = True
  244.             continue
  245.         if o in ('-L', '--runleaks'):
  246.             runleaks = True
  247.             continue
  248.         if o in ('-t', '--threshold'):
  249.             import gc
  250.             gc.set_threshold(int(a))
  251.             continue
  252.         if o in ('-T', '--coverage'):
  253.             trace = True
  254.             continue
  255.         if o in ('-D', '--coverdir'):
  256.             coverdir = os.path.join(os.getcwd(), a)
  257.             continue
  258.         if o in ('-N', '--nocoverdir'):
  259.             coverdir = None
  260.             continue
  261.         if o in ('-R', '--huntrleaks'):
  262.             huntrleaks = a.split(':')
  263.             if len(huntrleaks) != 3:
  264.                 print a, huntrleaks
  265.                 usage(2, '-R takes three colon-separated arguments')
  266.             
  267.             if len(huntrleaks[0]) == 0:
  268.                 huntrleaks[0] = 5
  269.             else:
  270.                 huntrleaks[0] = int(huntrleaks[0])
  271.             if len(huntrleaks[1]) == 0:
  272.                 huntrleaks[1] = 4
  273.             else:
  274.                 huntrleaks[1] = int(huntrleaks[1])
  275.             if len(huntrleaks[2]) == 0:
  276.                 huntrleaks[2] = 'reflog.txt'
  277.             
  278.         len(huntrleaks[2]) == 0
  279.         if o in ('-M', '--memlimit'):
  280.             test_support.set_memlimit(a)
  281.             continue
  282.         if o in ('-u', '--use'):
  283.             u = [ x.lower() for x in a.split(',') ]
  284.             for r in u:
  285.                 remove = False
  286.                 if r[0] == '-':
  287.                     remove = True
  288.                     r = r[1:]
  289.                 
  290.                 if r not in RESOURCE_NAMES:
  291.                     usage(1, 'Invalid -u/--use option: ' + a)
  292.                 
  293.                 if remove:
  294.                     if r in use_resources:
  295.                         use_resources.remove(r)
  296.                     
  297.                 r in use_resources
  298.                 if r not in use_resources:
  299.                     use_resources.append(r)
  300.                     continue
  301.             
  302.     
  303.     if single and fromfile:
  304.         usage(2, "-s and -f don't go together!")
  305.     
  306.     good = []
  307.     bad = []
  308.     skipped = []
  309.     resource_denieds = []
  310.     if findleaks:
  311.         
  312.         try:
  313.             import gc
  314.         except ImportError:
  315.             print 'No GC available, disabling findleaks.'
  316.             findleaks = False
  317.  
  318.         found_garbage = []
  319.     
  320.     if single:
  321.         gettempdir = gettempdir
  322.         import tempfile
  323.         filename = os.path.join(gettempdir(), 'pynexttest')
  324.         
  325.         try:
  326.             fp = open(filename, 'r')
  327.             next = fp.read().strip()
  328.             tests = [
  329.                 next]
  330.             fp.close()
  331.         except IOError:
  332.             pass
  333.         except:
  334.             None<EXCEPTION MATCH>IOError
  335.         
  336.  
  337.     None<EXCEPTION MATCH>IOError
  338.     if fromfile:
  339.         tests = []
  340.         fp = open(fromfile)
  341.         for line in fp:
  342.             guts = line.split()
  343.             if guts and not guts[0].startswith('#'):
  344.                 tests.extend(guts)
  345.                 continue
  346.         
  347.         fp.close()
  348.     
  349.     if args:
  350.         args = map(removepy, args)
  351.     
  352.     if tests:
  353.         tests = map(removepy, tests)
  354.     
  355.     stdtests = STDTESTS[:]
  356.     nottests = NOTTESTS[:]
  357.     if exclude:
  358.         for arg in args:
  359.             if arg in stdtests:
  360.                 stdtests.remove(arg)
  361.                 continue
  362.         
  363.         nottests[:0] = args
  364.         args = []
  365.     
  366.     if not tests and args:
  367.         pass
  368.     tests = findtests(testdir, stdtests, nottests)
  369.     if single:
  370.         tests = tests[:1]
  371.     
  372.     if randomize:
  373.         random.shuffle(tests)
  374.     
  375.     if trace:
  376.         import trace
  377.         tracer = trace.Trace(ignoredirs = [
  378.             sys.prefix,
  379.             sys.exec_prefix], trace = False, count = True)
  380.     
  381.     test_times = []
  382.     test_support.verbose = verbose
  383.     test_support.use_resources = use_resources
  384.     save_modules = sys.modules.keys()
  385.     for test in tests:
  386.         if not quiet:
  387.             print test
  388.             sys.stdout.flush()
  389.         
  390.         if trace:
  391.             tracer.runctx('runtest(test, verbose, quiet,        test_times, testdir)', globals = globals(), locals = vars())
  392.         else:
  393.             
  394.             try:
  395.                 ok = runtest(test, verbose, quiet, test_times, testdir, huntrleaks)
  396.             except KeyboardInterrupt:
  397.                 print 
  398.                 break
  399.             except:
  400.                 raise 
  401.  
  402.             if ok > 0:
  403.                 good.append(test)
  404.             elif ok == 0:
  405.                 bad.append(test)
  406.             else:
  407.                 skipped.append(test)
  408.                 if ok == -2:
  409.                     resource_denieds.append(test)
  410.                 
  411.         if findleaks:
  412.             gc.collect()
  413.             if gc.garbage:
  414.                 print 'Warning: test created', len(gc.garbage), 'uncollectable object(s).'
  415.                 found_garbage.extend(gc.garbage)
  416.                 del gc.garbage[:]
  417.             
  418.         
  419.         for module in sys.modules.keys():
  420.             if module not in save_modules and module.startswith('test.'):
  421.                 test_support.unload(module)
  422.                 continue
  423.         
  424.     
  425.     good.sort()
  426.     bad.sort()
  427.     skipped.sort()
  428.     if good and not quiet:
  429.         if not bad and not skipped and len(good) > 1:
  430.             print 'All',
  431.         
  432.         print count(len(good), 'test'), 'OK.'
  433.     
  434.     if print_slow:
  435.         test_times.sort(reverse = True)
  436.         print '10 slowest tests:'
  437.         for time, test in test_times[:10]:
  438.             print '%s: %.1fs' % (test, time)
  439.         
  440.     
  441.     if bad:
  442.         print count(len(bad), 'test'), 'failed:'
  443.         printlist(bad)
  444.     
  445.     if skipped and not quiet:
  446.         print count(len(skipped), 'test'), 'skipped:'
  447.         printlist(skipped)
  448.         e = _ExpectedSkips()
  449.         plat = sys.platform
  450.         if e.isvalid():
  451.             surprise = set(skipped) - e.getexpected() - set(resource_denieds)
  452.             if surprise:
  453.                 print count(len(surprise), 'skip'), 'unexpected on', plat + ':'
  454.                 printlist(surprise)
  455.             else:
  456.                 print 'Those skips are all expected on', plat + '.'
  457.         else:
  458.             print 'Ask someone to teach regrtest.py about which tests are'
  459.             print 'expected to get skipped on', plat + '.'
  460.     
  461.     if verbose2 and bad:
  462.         print 'Re-running failed tests in verbose mode'
  463.         for test in bad:
  464.             print 'Re-running test %r in verbose mode' % test
  465.             sys.stdout.flush()
  466.             
  467.             try:
  468.                 test_support.verbose = True
  469.                 ok = runtest(test, True, quiet, test_times, testdir, huntrleaks)
  470.             continue
  471.             except KeyboardInterrupt:
  472.                 print 
  473.                 break
  474.                 continue
  475.                 raise 
  476.                 continue
  477.             
  478.  
  479.         
  480.     
  481.     if single:
  482.         alltests = findtests(testdir, stdtests, nottests)
  483.         for i in range(len(alltests)):
  484.             if tests[0] == alltests[i]:
  485.                 if i == len(alltests) - 1:
  486.                     os.unlink(filename)
  487.                 else:
  488.                     fp = open(filename, 'w')
  489.                     fp.write(alltests[i + 1] + '\n')
  490.                     fp.close()
  491.                 break
  492.                 continue
  493.         
  494.     
  495.     if trace:
  496.         r = tracer.results()
  497.         r.write_results(show_missing = True, summary = True, coverdir = coverdir)
  498.     
  499.     if runleaks:
  500.         os.system('leaks %d' % os.getpid())
  501.     
  502.     sys.exit(len(bad) > 0)
  503.  
  504. STDTESTS = [
  505.     'test_grammar',
  506.     'test_opcodes',
  507.     'test_dict',
  508.     'test_builtin',
  509.     'test_exceptions',
  510.     'test_types',
  511.     'test_unittest',
  512.     'test_doctest',
  513.     'test_doctest2']
  514. NOTTESTS = [
  515.     'test_support',
  516.     'test_future1',
  517.     'test_future2']
  518.  
  519. def findtests(testdir = None, stdtests = STDTESTS, nottests = NOTTESTS):
  520.     '''Return a list of all applicable test modules.'''
  521.     if not testdir:
  522.         testdir = findtestdir()
  523.     
  524.     names = os.listdir(testdir)
  525.     tests = []
  526.     for name in names:
  527.         if name[:5] == 'test_' and name[-3:] == os.extsep + 'py':
  528.             modname = name[:-3]
  529.             if modname not in stdtests and modname not in nottests:
  530.                 tests.append(modname)
  531.             
  532.         modname not in nottests
  533.     
  534.     tests.sort()
  535.     return stdtests + tests
  536.  
  537.  
  538. def runtest(test, verbose, quiet, test_times, testdir = None, huntrleaks = False):
  539.     """Run a single test.
  540.  
  541.     test -- the name of the test
  542.     verbose -- if true, print more messages
  543.     quiet -- if true, don't print 'skipped' messages (probably redundant)
  544.     test_times -- a list of (time, test_name) pairs
  545.     testdir -- test directory
  546.     huntrleaks -- run multiple times to test for leaks; requires a debug
  547.                   build; a triple corresponding to -R's three arguments
  548.     Return:
  549.         -2  test skipped because resource denied
  550.         -1  test skipped for some other reason
  551.          0  test failed
  552.          1  test passed
  553.     """
  554.     
  555.     try:
  556.         return runtest_inner(test, verbose, quiet, test_times, testdir, huntrleaks)
  557.     finally:
  558.         cleanup_test_droppings(test, verbose)
  559.  
  560.  
  561.  
  562. def runtest_inner(test, verbose, quiet, test_times, testdir = None, huntrleaks = False):
  563.     test_support.unload(test)
  564.     if not testdir:
  565.         testdir = findtestdir()
  566.     
  567.     if verbose:
  568.         capture_stdout = None
  569.     else:
  570.         capture_stdout = cStringIO.StringIO()
  571.     
  572.     try:
  573.         save_stdout = sys.stdout
  574.         
  575.         try:
  576.             if capture_stdout:
  577.                 sys.stdout = capture_stdout
  578.             
  579.             if test.startswith('test.'):
  580.                 abstest = test
  581.             else:
  582.                 abstest = 'test.' + test
  583.             start_time = time.time()
  584.             the_package = __import__(abstest, globals(), locals(), [])
  585.             the_module = getattr(the_package, test)
  586.             indirect_test = getattr(the_module, 'test_main', None)
  587.             if indirect_test is not None:
  588.                 indirect_test()
  589.             
  590.             if huntrleaks:
  591.                 dash_R(the_module, test, indirect_test, huntrleaks)
  592.             
  593.             test_time = time.time() - start_time
  594.             test_times.append((test_time, test))
  595.         finally:
  596.             sys.stdout = save_stdout
  597.  
  598.     except test_support.ResourceDenied:
  599.         msg = None
  600.         if not quiet:
  601.             print test, 'skipped --', msg
  602.             sys.stdout.flush()
  603.         
  604.         return -2
  605.         except (ImportError, test_support.TestSkipped):
  606.             msg = None
  607.             if not quiet:
  608.                 print test, 'skipped --', msg
  609.                 sys.stdout.flush()
  610.             
  611.             return -1
  612.             except KeyboardInterrupt:
  613.                 raise 
  614.             except test_support.TestFailed:
  615.                 msg = None
  616.                 print 'test', test, 'failed --', msg
  617.                 sys.stdout.flush()
  618.                 return 0
  619.                 (type, value) = sys.exc_info()[:2]
  620.                 print 'test', test, 'crashed --', str(type) + ':', value
  621.                 sys.stdout.flush()
  622.                 if verbose:
  623.                     traceback.print_exc(file = sys.stdout)
  624.                     sys.stdout.flush()
  625.                 
  626.     return 0
  627.  
  628.     if verbose or huntrleaks:
  629.         return 1
  630.     output = capture_stdout.getvalue()
  631.     if not output:
  632.         return 1
  633.     print 'test', test, 'produced unexpected output:'
  634.     print '*' * 70
  635.     print output
  636.     print '*' * 70
  637.     sys.stdout.flush()
  638.     return 0
  639.  
  640.  
  641. def cleanup_test_droppings(testname, verbose):
  642.     import shutil
  643.     for name in (test_support.TESTFN, 'db_home'):
  644.         if not os.path.exists(name):
  645.             continue
  646.         
  647.         if os.path.isdir(name):
  648.             kind = 'directory'
  649.             nuker = shutil.rmtree
  650.         elif os.path.isfile(name):
  651.             kind = 'file'
  652.             nuker = os.unlink
  653.         else:
  654.             raise SystemError('os.path says %r exists but is neither directory nor file' % name)
  655.         if os.path.isdir(name):
  656.             print '%r left behind %s %r' % (testname, kind, name)
  657.         
  658.         
  659.         try:
  660.             nuker(name)
  661.         continue
  662.         except Exception:
  663.             msg = None
  664.             print >>sys.stderr, "%r left behind %s %r and it couldn't be removed: %s" % (testname, kind, name, msg)
  665.             continue
  666.         
  667.  
  668.     
  669.  
  670.  
  671. def dash_R(the_module, test, indirect_test, huntrleaks):
  672.     import copy_reg
  673.     import _abcoll
  674.     import io
  675.     if not hasattr(sys, 'gettotalrefcount'):
  676.         raise Exception('Tracking reference leaks requires a debug build of Python')
  677.     hasattr(sys, 'gettotalrefcount')
  678.     fs = warnings.filters[:]
  679.     ps = copy_reg.dispatch_table.copy()
  680.     pic = sys.path_importer_cache.copy()
  681.     abcs = { }
  682.     modules = (_abcoll, io)
  683.     for mod in modules:
  684.         pass
  685.     
  686.     deltas = []
  687.     (nwarmup, ntracked, fname) = huntrleaks
  688.     repcount = nwarmup + ntracked
  689.     print >>sys.stderr, 'beginning', repcount, 'repetitions'
  690.     print >>sys.stderr, '1234567890' * (repcount // 10 + 1)[:repcount]
  691.     dash_R_cleanup(fs, ps, pic, abcs)
  692.     for i in range(repcount):
  693.         rc = sys.gettotalrefcount()
  694.         run_the_test()
  695.         sys.stderr.write('.')
  696.         dash_R_cleanup(fs, ps, pic, abcs)
  697.         if i >= nwarmup:
  698.             deltas.append(sys.gettotalrefcount() - rc - 2)
  699.             continue
  700.     
  701.     print >>sys.stderr
  702.     if any(deltas):
  703.         msg = '%s leaked %s references, sum=%s' % (test, deltas, sum(deltas))
  704.         print >>sys.stderr, msg
  705.         refrep = open(fname, 'a')
  706.         print >>refrep, msg
  707.         refrep.close()
  708.     
  709.  
  710.  
  711. def dash_R_cleanup(fs, ps, pic, abcs):
  712.     import gc
  713.     import copy_reg
  714.     import _strptime
  715.     import linecache
  716.     dircache = test_support.import_module('dircache', deprecated = True)
  717.     import urlparse
  718.     import urllib
  719.     import urllib2
  720.     import mimetypes
  721.     import doctest
  722.     import struct
  723.     import filecmp
  724.     _path_created = _path_created
  725.     import distutils.dir_util
  726.     for mod in sys.modules.values():
  727.         if hasattr(mod, '__warningregistry__'):
  728.             del mod.__warningregistry__
  729.             continue
  730.     
  731.     warnings.filters[:] = fs
  732.     copy_reg.dispatch_table.clear()
  733.     copy_reg.dispatch_table.update(ps)
  734.     sys.path_importer_cache.clear()
  735.     sys.path_importer_cache.update(pic)
  736.     sys._clear_type_cache()
  737.     for abc, registry in abcs.items():
  738.         abc._abc_registry = registry.copy()
  739.         abc._abc_cache.clear()
  740.         abc._abc_negative_cache.clear()
  741.     
  742.     _path_created.clear()
  743.     re.purge()
  744.     _strptime._regex_cache.clear()
  745.     urlparse.clear_cache()
  746.     urllib.urlcleanup()
  747.     urllib2.install_opener(None)
  748.     dircache.reset()
  749.     linecache.clearcache()
  750.     mimetypes._default_mime_types()
  751.     filecmp._cache.clear()
  752.     struct._clearcache()
  753.     doctest.master = None
  754.     gc.collect()
  755.  
  756.  
  757. def findtestdir():
  758.     if __name__ == '__main__':
  759.         file = sys.argv[0]
  760.     else:
  761.         file = __file__
  762.     if not os.path.dirname(file):
  763.         pass
  764.     testdir = os.curdir
  765.     return testdir
  766.  
  767.  
  768. def removepy(name):
  769.     if name.endswith(os.extsep + 'py'):
  770.         name = name[:-3]
  771.     
  772.     return name
  773.  
  774.  
  775. def count(n, word):
  776.     if n == 1:
  777.         return '%d %s' % (n, word)
  778.     return '%d %ss' % (n, word)
  779.  
  780.  
  781. def printlist(x, width = 70, indent = 4):
  782.     '''Print the elements of iterable x to stdout.
  783.  
  784.     Optional arg width (default 70) is the maximum line length.
  785.     Optional arg indent (default 4) is the number of blanks with which to
  786.     begin each line.
  787.     '''
  788.     fill = fill
  789.     import textwrap
  790.     blanks = ' ' * indent
  791.     print fill(' '.join(map(str, x)), width, initial_indent = blanks, subsequent_indent = blanks)
  792.  
  793. _expectations = {
  794.     'win32': '\n        test__locale\n        test_bsddb185\n        test_bsddb3\n        test_commands\n        test_crypt\n        test_curses\n        test_dbm\n        test_dl\n        test_fcntl\n        test_fork1\n        test_epoll\n        test_gdbm\n        test_grp\n        test_ioctl\n        test_largefile\n        test_kqueue\n        test_mhlib\n        test_openpty\n        test_ossaudiodev\n        test_pipes\n        test_poll\n        test_posix\n        test_pty\n        test_pwd\n        test_resource\n        test_signal\n        test_threadsignals\n        test_timing\n        test_wait3\n        test_wait4\n        ',
  795.     'linux2': '\n        test_bsddb185\n        test_curses\n        test_dl\n        test_largefile\n        test_kqueue\n        test_ossaudiodev\n        ',
  796.     'mac': '\n        test_atexit\n        test_bsddb\n        test_bsddb185\n        test_bsddb3\n        test_bz2\n        test_commands\n        test_crypt\n        test_curses\n        test_dbm\n        test_dl\n        test_fcntl\n        test_fork1\n        test_epoll\n        test_grp\n        test_ioctl\n        test_largefile\n        test_locale\n        test_kqueue\n        test_mmap\n        test_openpty\n        test_ossaudiodev\n        test_poll\n        test_popen\n        test_popen2\n        test_posix\n        test_pty\n        test_pwd\n        test_resource\n        test_signal\n        test_sundry\n        test_tarfile\n        test_timing\n        ',
  797.     'unixware7': '\n        test_bsddb\n        test_bsddb185\n        test_dl\n        test_epoll\n        test_largefile\n        test_kqueue\n        test_minidom\n        test_openpty\n        test_pyexpat\n        test_sax\n        test_sundry\n        ',
  798.     'openunix8': '\n        test_bsddb\n        test_bsddb185\n        test_dl\n        test_epoll\n        test_largefile\n        test_kqueue\n        test_minidom\n        test_openpty\n        test_pyexpat\n        test_sax\n        test_sundry\n        ',
  799.     'sco_sv3': '\n        test_asynchat\n        test_bsddb\n        test_bsddb185\n        test_dl\n        test_fork1\n        test_epoll\n        test_gettext\n        test_largefile\n        test_locale\n        test_kqueue\n        test_minidom\n        test_openpty\n        test_pyexpat\n        test_queue\n        test_sax\n        test_sundry\n        test_thread\n        test_threaded_import\n        test_threadedtempfile\n        test_threading\n        ',
  800.     'riscos': '\n        test_asynchat\n        test_atexit\n        test_bsddb\n        test_bsddb185\n        test_bsddb3\n        test_commands\n        test_crypt\n        test_dbm\n        test_dl\n        test_fcntl\n        test_fork1\n        test_epoll\n        test_gdbm\n        test_grp\n        test_largefile\n        test_locale\n        test_kqueue\n        test_mmap\n        test_openpty\n        test_poll\n        test_popen2\n        test_pty\n        test_pwd\n        test_strop\n        test_sundry\n        test_thread\n        test_threaded_import\n        test_threadedtempfile\n        test_threading\n        test_timing\n        ',
  801.     'darwin': '\n        test__locale\n        test_bsddb\n        test_bsddb3\n        test_curses\n        test_epoll\n        test_gdbm\n        test_largefile\n        test_locale\n        test_kqueue\n        test_minidom\n        test_ossaudiodev\n        test_poll\n        ',
  802.     'sunos5': '\n        test_bsddb\n        test_bsddb185\n        test_curses\n        test_dbm\n        test_epoll\n        test_kqueue\n        test_gdbm\n        test_gzip\n        test_openpty\n        test_zipfile\n        test_zlib\n        ',
  803.     'hp-ux11': '\n        test_bsddb\n        test_bsddb185\n        test_curses\n        test_dl\n        test_epoll\n        test_gdbm\n        test_gzip\n        test_largefile\n        test_locale\n        test_kqueue\n        test_minidom\n        test_openpty\n        test_pyexpat\n        test_sax\n        test_zipfile\n        test_zlib\n        ',
  804.     'atheos': '\n        test_bsddb185\n        test_curses\n        test_dl\n        test_gdbm\n        test_epoll\n        test_largefile\n        test_locale\n        test_kqueue\n        test_mhlib\n        test_mmap\n        test_poll\n        test_popen2\n        test_resource\n        ',
  805.     'cygwin': '\n        test_bsddb185\n        test_bsddb3\n        test_curses\n        test_dbm\n        test_epoll\n        test_ioctl\n        test_kqueue\n        test_largefile\n        test_locale\n        test_ossaudiodev\n        test_socketserver\n        ',
  806.     'os2emx': '\n        test_audioop\n        test_bsddb185\n        test_bsddb3\n        test_commands\n        test_curses\n        test_dl\n        test_epoll\n        test_kqueue\n        test_largefile\n        test_mhlib\n        test_mmap\n        test_openpty\n        test_ossaudiodev\n        test_pty\n        test_resource\n        test_signal\n        ',
  807.     'freebsd4': '\n        test_bsddb\n        test_bsddb3\n        test_epoll\n        test_gdbm\n        test_locale\n        test_ossaudiodev\n        test_pep277\n        test_pty\n        test_socket_ssl\n        test_socketserver\n        test_tcl\n        test_timeout\n        test_urllibnet\n        test_multiprocessing\n        ',
  808.     'aix5': '\n        test_bsddb\n        test_bsddb185\n        test_bsddb3\n        test_bz2\n        test_dl\n        test_epoll\n        test_gdbm\n        test_gzip\n        test_kqueue\n        test_ossaudiodev\n        test_tcl\n        test_zipimport\n        test_zlib\n        ',
  809.     'openbsd3': '\n        test_bsddb\n        test_bsddb3\n        test_ctypes\n        test_dl\n        test_epoll\n        test_gdbm\n        test_locale\n        test_normalization\n        test_ossaudiodev\n        test_pep277\n        test_tcl\n        test_multiprocessing\n        ',
  810.     'netbsd3': '\n        test_bsddb\n        test_bsddb185\n        test_bsddb3\n        test_ctypes\n        test_curses\n        test_dl\n        test_epoll\n        test_gdbm\n        test_locale\n        test_ossaudiodev\n        test_pep277\n        test_tcl\n        test_multiprocessing\n        ' }
  811. _expectations['freebsd5'] = _expectations['freebsd4']
  812. _expectations['freebsd6'] = _expectations['freebsd4']
  813. _expectations['freebsd7'] = _expectations['freebsd4']
  814. _expectations['freebsd8'] = _expectations['freebsd4']
  815.  
  816. class _ExpectedSkips:
  817.     
  818.     def __init__(self):
  819.         import os.path as os
  820.         test_timeout = test_timeout
  821.         import test
  822.         self.valid = False
  823.         if sys.platform in _expectations:
  824.             s = _expectations[sys.platform]
  825.             self.expected = set(s.split())
  826.             self.expected.add('test_linuxaudiodev')
  827.             if not os.path.supports_unicode_filenames:
  828.                 self.expected.add('test_pep277')
  829.             
  830.             
  831.             try:
  832.                 test_socket_ssl = test_socket_ssl
  833.                 import test
  834.             except ImportError:
  835.                 pass
  836.  
  837.             if test_socket_ssl.skip_expected:
  838.                 self.expected.add('test_socket_ssl')
  839.             
  840.             if test_timeout.skip_expected:
  841.                 self.expected.add('test_timeout')
  842.             
  843.             if sys.maxint == 0x7FFFFFFFFFFFFFFFL:
  844.                 self.expected.add('test_imageop')
  845.             
  846.             if sys.platform not in ('mac', 'darwin'):
  847.                 MAC_ONLY = [
  848.                     'test_macos',
  849.                     'test_macostools',
  850.                     'test_aepack',
  851.                     'test_plistlib',
  852.                     'test_scriptpackages',
  853.                     'test_applesingle']
  854.                 for skip in MAC_ONLY:
  855.                     self.expected.add(skip)
  856.                 
  857.             elif len(u'\x00'.encode('unicode-internal')) == 4:
  858.                 self.expected.add('test_macostools')
  859.             
  860.             if sys.platform != 'win32':
  861.                 WIN_ONLY = [
  862.                     'test_unicode_file',
  863.                     'test_winreg',
  864.                     'test_winsound',
  865.                     'test_startfile',
  866.                     'test_sqlite']
  867.                 for skip in WIN_ONLY:
  868.                     self.expected.add(skip)
  869.                 
  870.             
  871.             if sys.platform != 'irix':
  872.                 IRIX_ONLY = [
  873.                     'test_imageop',
  874.                     'test_al',
  875.                     'test_cd',
  876.                     'test_cl',
  877.                     'test_gl',
  878.                     'test_imgfile']
  879.                 for skip in IRIX_ONLY:
  880.                     self.expected.add(skip)
  881.                 
  882.             
  883.             if sys.platform != 'sunos5':
  884.                 self.expected.add('test_sunaudiodev')
  885.                 self.expected.add('test_nis')
  886.             
  887.             if not sys.py3kwarning:
  888.                 self.expected.add('test_py3kwarn')
  889.             
  890.             self.valid = True
  891.         
  892.  
  893.     
  894.     def isvalid(self):
  895.         '''Return true iff _ExpectedSkips knows about the current platform.'''
  896.         return self.valid
  897.  
  898.     
  899.     def getexpected(self):
  900.         '''Return set of test names we expect to skip on current platform.
  901.  
  902.         self.isvalid() must be true.
  903.         '''
  904.         if not self.isvalid():
  905.             raise AssertionError
  906.         return self.expected
  907.  
  908.  
  909. if __name__ == '__main__':
  910.     mydir = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
  911.     i = pathlen = len(sys.path)
  912.     while i >= 0:
  913.         i -= 1
  914.         if os.path.abspath(os.path.normpath(sys.path[i])) == mydir:
  915.             del sys.path[i]
  916.         
  917.     if len(sys.path) == pathlen:
  918.         print 'Could not find %r in sys.path to remove it' % mydir
  919.     
  920.     main()
  921.  
  922.